#!/usr/bin/python
# -*- coding: utf-8 -*-
""" @namespace QCMusical
Start methods and interface configuration


Copyright 2007, NATE-LSI-EPUSP

QCMusical is developed in Brazil at Escola Politécnica of 
Universidade de São Paulo. NATE is part of LSI (Integrable
Systems Laboratory) and stands for Learning, Work and Entertainment
Research Group. Visit our web page: 
www.lsi.usp.br/nate
Suggestions, bugs and doubts, please email nate-lsi@googlegroups.com
or get in http://code.google.com/p/qcmusical/

QCMusical is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License 
as published by the Free Software Foundation version 2 of 
the License.

QCMusical is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public
License along with Oficina; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, 
Boston, MA  02110-1301  USA.
The copy of the GNU General Public License is found in the 
COPYING file included in the source distribution.


Authors:
Pedro Kayatt                        (pekayatt@gmail.com)

Group Manager:
Irene Karaguilla Ficheman           (irene@lsi.usp.br)

Cientific Coordinator:
Roseli de Deus Lopes                (roseli@lsi.usp.br)

"""
from Panel import *
import os, sys
#including pygame library
import pygame, pygame.mixer
from pygame.locals import *



try:
    from sugar.activity.activity import get_bundle_path
except ImportError:
    def get_bundle_path():
        return ''
##Patch where images are store
images_dir = os.path.join( get_bundle_path(), "imagens" )
##Patch where sounds are store
sounds_dir = os.path.join( get_bundle_path(), "sounds" )

##This is the main class. In it we select the levels, difficult and verify if the sequence is right
class QCMusical(object):

    ##this fish represents the EASY level
    fish1      = None
    ##this fish represents the HARD level
    fish2      = None

    ##While run is True game still running
    run         = True

    ##difsel is the difficult flag:
    #  -If difsel = 1 then difficult = easy,
    #  -If difsel = 2 then difficult = hard,
    #  -If difsel = 3 user need select and difficult .
    difsel      = 3
    
    ##Says which level will be play.
    level       = 0
    ##comb is the array where the right combination of pieces successfully end the game.
    comb        = []
    ##this array tell us which level is already successfully done.
    levelFinish = [False,False,False,False,False,False,False,False,False,False,False]

    lampyellow = [ 0,1,2,3,4,5]  
    lampred = [ 0,1,2,3,4,5]
    
    ##Store the bridge images on Easy Difficult
    image_bridgeEasy = [0,0,0,0,0,0]
    ##Store the bridge images on HARD Difficult
    image_bridgeHard = [0,0,0,0]
    ##How many pieces of bridge the player get?
    bridge = 0
    ##A simples score system
    score = 0
    scoreMsg = None

    ##The constructor
    def __init__( self, fullscreen=False ):
     
        ###Initialize pygame module
        pygame.init()
        pygame.mixer.init()
        
        ##Set the size of the screen, default for XO with Sugar-Toolbar is 1200-825
        self.screen       = pygame.display.set_mode((1200,825))
        
        for i in range(11):#inicializacao da lista de comb certas para cada fase
    	    self.comb.append([])
            for j in range(11):
                self.comb[i].append(0)
        
        self.load_images()

        for i in range(6):
            self.lampyellow[i] = self.image_lampyellow1
        for i in range(4):  
            self.lampred[i] = self.image_lampred1

        self.fish1 = self.image_fish_easy0
        self.fish2 = self.image_fish_hard0
        
        pygame.mouse.set_visible(True)
        pygame.display.set_caption( 'Quebra-Cabeca Musical' )

    def load_images(self):
        """
        Load all images

        @param self   QCMusical object
        
        """
        
        def load_image( filename ):
            img = pygame.image.load(filename)
            img.set_alpha( None, RLEACCEL ) # disable alpha.
            img = img.convert()
            img.set_colorkey( ( 255, 0, 255 ), RLEACCEL ) # magenta
            return img
        # load_image()
        
        p  = images_dir + os.path.sep
        self.image_bg           = load_image( p + "fundo.png")       
        self.image_fish_easy0   = load_image( p + "peixeF0.png" )
        self.image_fish_easy1   = load_image( p + "peixeF1.png" )
        self.image_fish_hard0   = load_image( p + "peixeD0.png" )
        self.image_fish_hard1   = load_image( p + "peixeD1.png" )
        self.image_lampyellow1  = load_image( p + "lamp_amarela.png" )
        self.image_lampyellow2  = load_image( p + "lamp_amarela_acessa.png" )
        self.image_lampred1     = load_image( p + "lamp_vermelha.png" )
        self.image_lampred2     = load_image( p + "lamp_vermelha_acessa.png" )
        self.image_statusbar    = load_image( p + "statusbar.png" )
        self.image_wood1        = load_image( p + "mato1.png")
        
        self.image_bridgeEasy[0] = load_image( p + "pontef0.png")
        self.image_bridgeEasy[1] = load_image( p + "pontef1.png")
        self.image_bridgeEasy[2] = load_image( p + "pontef2.png")
        self.image_bridgeEasy[3] = load_image( p + "pontef3.png")
        self.image_bridgeEasy[4] = load_image( p + "pontef4.png")
        self.image_bridgeEasy[5] = load_image( p + "pontef5.png")
        
        self.image_bridgeHard[0] = load_image(p + "ponted0.png")
        self.image_bridgeHard[1] = load_image(p + "ponted1.png")
        self.image_bridgeHard[2] = load_image(p + "ponted2.png")
        self.image_bridgeHard[3] = load_image(p + "ponted3.png")
    # load_images()

    def load_sounds(self):
        """
        Load musics
        
        @param self   QCMusical object
        
        """
        s = sounds_dir + os.path.sep
        self.sound1 =  s + "DancaHungara.ogg"
        self.sound2 =  s + "MorningMood.ogg"
        self.sound3 =  s + "AssimfalavaZaratustra.ogg"
        self.sound4 =  s + "IlCatalogoEhQuesto.ogg"
        self.sound5 =  s + "Cantilena.ogg"
        #self.sound6 =  s + "Brasileirinho.ogg"
        
        self.sound7 =  s + "HallOfTheMountainKing.ogg"
        self.sound8 =  s + "YoureTheWeaverOfDreams.ogg"
        self.sound9 =  s + "BoleroDeRavel.ogg"
        #self.sound10 = s + "PelaInternet.ogg"

    def handle_events(self):
        """
        Handle events

        @param self   QCMusical object
        
        A list of events:
            -keyboard events
                -#key = K_ESCAPE -> Quit from program
            -mouse events
                -On Mouse Motion
                    -#if difsel = 0 or 1 -> Turn on or off the lamps\n
                      else send msg to click in one fish
                -On Mouse Down
                    -#Start on of the levels
        
        """
        for event in pygame.event.get():

            pos = pygame.mouse.get_pos()
            t = event.type
            k = None

            if t in ( KEYDOWN, KEYUP ):
                k = event.key
        
            if t == QUIT:
                self.run = False

            elif t == KEYDOWN:
                if   k == K_ESCAPE:
                    self.run = False

            if (t == MOUSEMOTION):# and (self.level==0):
                
                if (self.difsel==0):
                    #lampadas amarelas
                    if (40<=pos[0]<=85) and (155<=pos[1]<=210) and (self.levelFinish[1]!=True):
                        self.lampyellow[0] = self.image_lampyellow2
                        self.panel.msg="Danca Hungara n05 - Johannes Brahms"
                    elif (220<=pos[0]<=270) and (120<=pos[1]<=190)and (self.levelFinish[2]!=True) :
                        self.lampyellow[1] = self.image_lampyellow2   
                        self.panel.msg="Morning Mood - Edvard Grieg"
                    elif (455<=pos[0]<=510) and (60<=pos[1]<=130) and (self.levelFinish[3]!=True):
                        self.lampyellow[2] = self.image_lampyellow2  
                        self.panel.msg="Assim falava Zaratustra - Richard Strauss"  
                    elif (585<=pos[0]<=640) and (115<=pos[1]<=190)and (self.levelFinish[4]!=True) :
                        self.lampyellow[3] = self.image_lampyellow2   
                        self.panel.msg="Il catalogo e questo - W. A Mozart" 
                    elif (840<=pos[0]<=890) and (60<=pos[1]<=132)and (self.levelFinish[5]!=True) :
                        self.lampyellow[4] = self.image_lampyellow2   
                        self.panel.msg="Cantilena - Heitor Villa-Lobos" 
                    elif (955<=pos[0]<=1010) and (100<=pos[1]<=180)and (self.levelFinish[6]!=True) :
                        self.lampyellow[5] = self.image_lampyellow2 
                        self.panel.msg="Brasileirinho"   
                    else :
                        for i in range(6):                    
                            self.lampyellow[i] = self.image_lampyellow1
                        if (self.level==0):
                            self.panel.msg="Difficult EASY selected. Choose one lamp to start the level."
                            #self.panel.msg="Nivel facil selecionado. Clique nas lampadas para escolher o desafio"
                        
                                

                elif (self.difsel==1):
                    #lampadas vermelhas
                    if (120<=pos[0]<=170) and (110<=pos[1]<=180) and (self.levelFinish[7]!=True):
                        self.lampred[0] = self.image_lampred2
                        self.panel.msg="In the Hall of the mountain King - Edvard Grieg"
                    elif (340<=pos[0]<=390) and (180<=pos[1]<=255)and (self.levelFinish[8]!=True) :
                        self.lampred[1] = self.image_lampred2
                        self.panel.msg="You're a weaver in dreams - Young-Elliot"
                    elif (700<=pos[0]<=750) and (70<=pos[1]<=140) and (self.levelFinish[9]!=True):
                        self.lampred[2] = self.image_lampred2
                        self.panel.msg="Bolero - Maurice Ravel"
                    elif (1085<=pos[0]<=1140) and (70<=pos[1]<=140) and (self.levelFinish[10]!=True):
                        self.lampred[3] = self.image_lampred2
                        self.panel.msg="Pela Internet"
                    else :
                        for i in range(4):                    
                            self.lampred[i] = self.image_lampred1
                        if (self.level==0):
                            self.panel.msg="Difficult HARD selected. Choose one lamp to start the level."
                            #self.panel.msg="Nivel dificil selecionado. Clique nas lampadas para escolher o desafio"

                else :
                    if (380<=pos[0]<=490) and (720-75<=pos[1]<=775-75)and (self.levelFinish[1]!=True):
                        self.fish1 = self.image_fish_easy1
                        self.panel.msg= "Click to select the EASY difficult"
                        #self.panel.msg= "Clique para selecionar o nivel facil"
                    elif (550<=pos[0]<=740) and (730-75<=pos[1]<=825-75)and (self.levelFinish[7]!=True):
                        self.fish2 = self.image_fish_hard1
                        self.panel.msg= "Click to select the HARD difficult"              
                        #self.panel.msg= "Clique para selecionar o nivel dificil"
                    else :
                        self.fish1 = self.image_fish_easy0
                        self.fish2 = self.image_fish_hard0
                        if (self.levelFinish[0]):
                            self.panel.msg = "Congratulations you done all levels of onde difficult!!!\
                                                To finish the game you need done all levels"
                            #self.panel.msg = "Parabens voce completou os desafios de um nivel. \
                            #                    Para completar o jogo termine todos desafios"
                        else:
                            self.panel.msg= "Click in one fish to START."
                            #self.panel.msg= "Clique num peixe para comecar."
                 
     
            #mousemotion
            elif (t == MOUSEBUTTONDOWN) :
                #print self.levelFinish
                #print pygame.mouse.get_pos()
                    
                if (self.difsel == 3):                
                    if (380<=pos[0]<=490) and (720-75<=pos[1]<=775-75) and (self.levelFinish[1]!=True):
                        self.difsel = 0
                        self.panel.msg="Difficult EASY selected. Choose one lamp to start the level."
                        #self.panel.msg="Nivel facil selecionado. Clique nas lampadas para escolher o desafio"
                        
                    if (550<=pos[0]<=740) and (730-75<=pos[1]<=825-75) and (self.levelFinish[7]!=True):
                        self.difsel = 1
                        self.panel.msg="Difficult HARD selected. Choose one lamp to start the level."
                        #self.panel.msg="Nivel dificil selecionado. Clique nas lampadas para escolher o desafio"
                
                elif (self.difsel == 0):
                    if (40<=pos[0]<=85) and (155<=pos[1]<=210) and (self.levelFinish[1]!=True):
                        self.level = 1
                        self.panel.start_level()                  
                        self.panel.msg="Danca Hungara n05 - Johannes Brahms"
                        self.panel.playSong(self.level)
                    elif (220<=pos[0]<=270) and (120<=pos[1]<=190) and (not self.levelFinish[2]):
                        self.level = 2
                        self.panel.start_level()
                        self.panel.msg="Morning Mood - Edvard Grieg"
                        self.panel.playSong(self.level)
                    elif (455<=pos[0]<=510) and (60<=pos[1]<=130) and (self.levelFinish[3]!=True):
                        self.level = 3
                        self.panel.start_level()
                        self.panel.msg="Assim falava Zaratustra - Richard Strauss"
                        self.panel.playSong(self.level)
                    elif (585<=pos[0]<=640) and (115<=pos[1]<=190) and (self.levelFinish[4]!=True):
                        self.level = 4
                        self.panel.start_level()
                        self.panel.msg="Il catalogo e questo - W. A Mozart"
                        self.panel.playSong(self.level)
                    elif (840<=pos[0]<=890) and (60<=pos[1]<=132) and (self.levelFinish[5]!=True):
                        self.level = 5
                        self.panel.start_level()
                        self.panel.msg="Cantilena - Heitor Villa-Lobos"
                        self.panel.playSong(self.level)
                    elif (955<=pos[0]<=1010) and (100<=pos[1]<=180) and (self.levelFinish[6]!=True):
                        self.level = 6
                        self.panel.start_level()
                        self.panel.msg="Brasileirinho"
                        #pygame.mixer.music.load(self.sound6)
                        #pygame.mixer.music.play()
                        #while pygame.mixer.music.get_busy():
                        #    pygame.event.wait();

                elif (self.difsel == 1):
                    if (120<=pos[0]<=170) and (110<=pos[1]<=180) and (self.levelFinish[7]!=True):
                        self.level = 7
                        self.panel.start_level()
                        self.panel.msg="In the Hall of the mountain King - Edvard Grieg"
                        self.panel.playSong(self.level)
                    elif (340<=pos[0]<=390) and (180<=pos[1]<=255) and (self.levelFinish[8]!=True):
                        self.level = 8
                        self.panel.start_level()
                        self.panel.msg="You're a weaver in dreams - Young-Elliot"
                        self.panel.playSong(self.level)
                    elif (700<=pos[0]<=750) and (70<=pos[1]<=140) and (self.levelFinish[9]!=True):
                        self.level = 9
                        self.panel.start_level()
                        self.panel.msg="Bolero - Maurice Ravel"
                        self.panel.playSong(self.level)
                    elif (1085<=pos[0]<=1140) and (70<=pos[1]<=140) and (self.levelFinish[10]!=True):
                        self.level = 10
                        self.panel.start_level()
                        self.panel.msg="Pela Internet"

                if (self.level!=0):
                    if (0<pos[0]<25) and (600<pos[1]<625):#close panel
                        self.level=0
                    if (1105<pos[0]<1155) and (625<pos[1]<660):#tip
                        self.panel.playSong(self.level)
                        if (self.score>=15):
                            self.score-=15
                    if (900<pos[0]<1010) and (585<pos[1]<725):
                        self.verify(self.level, self.panel.slotPiece,self.difsel)    

                self.panel.level=self.level
                self.panel.difsel=self.difsel  

            if (self.level!=0):
                self.panel.events(t,k,pos)
                
            #When finish one difficult   
            if ((self.levelFinish==[False,True,True,True,True,True,False,False,False,False,False]) or \
                (self.levelFinish==[False,False,False,False,False,False,False,True,True,True,False]) ):
                self.difsel=3    
                self.bridge=0
                self.level=0
                self.levelFinish[0]=True
                self.panel.start_level()

                
    def atualizaPonte(self):
        """
        When you sucesseful done one game match, the brigde will update
        
        @param self   QCMusical object
        
        """
        if (self.difsel==0):
            self.score+=40
        elif (self.difsel==1):
            self.score+=80    
        self.bridge+=1
    
    def verify(self, level, matchPiece, difsel):
        """
        Verify if the order of pieces is right
        
        @param self         QCMusical object
        @param level        The level who needs be verified
        @param matchPiece   Array with pieces on slots
        @param difsel       Selected difficult 
        """
        finished = True
        
        self.score-=5
                    
        #Here you can change the order os the sound pieces
        #PS:Don't forget to change the correlation os sounds with pieces  
        if (difsel==0):        
            self.comb[1] = (0,2,1,3,4)
            self.comb[2] = (0,3,2,1,4)
            self.comb[3] = (0,4,2,3,1)
            self.comb[4] = (0,4,3,2,1)
            self.comb[5] = (0,1,4,2,3)
            self.comb[6] = (0,1,2,3,4)
            for i in range(1,5):
                if matchPiece[i]!=self.comb[level][i]:
                    self.panel.piece_msg = "Piece %d is wrong" %(i)
                    #self.panel.piece_msg = "Peca %d errada" %(i)
                    finished = False
                    break
                
        elif (difsel==1) :
            self.comb[7] = (0,2,3,6,1,5,7,8,4)
            self.comb[8] = (0,6,4,3,7,2,5,8,1)
            self.comb[9] = (0,3,8,4,5,1,2,7,6)
            self.comb[10] = (0,1,2,3,4,5,6,7,8)
            for i in range(1,9):
                if matchPiece[i]!=self.comb[level][i]:
                    self.panel.piece_msg = "Piece %d wrong" %(i)
                    #self.panel.piece_msg = "Peca %d errada" %(i)
                    finished = False
                    break
        
        if finished:
            self.panel.msg = "LEVEL FINISHED!! WELL DONE!"
            #self.panel.msg = "Desafio Completo!"
            self.panel.piece_msg = ""
            self.atualizaPonte()
            self.panel.playSong(level)
            self.levelFinish[level]=True;
            #zerando as config do panel
            self.level=0
            self.panel.start_level()
            

    def actors_draw(self):
        """
        Draw the imagens on screen
        
        @param self   QCMusical object
        
        """
        lamp_pos = ((35,-75),  (220,-100), (455,-160),   (583,-105), (835,-160), (955,-115),\
                    (120,-165), (337,-95),   (695,-205) , (1085,-105) )
                    
        #background
        self.screen.blit(self.image_bg, (0,0))
        
        if (self.difsel!=1) :
            for i in range(5):
                if (self.levelFinish[i+1]!=True):
                    self.screen.blit(self.lampyellow[i], lamp_pos[i] )
        if (self.difsel!=0) :
            for i in range(6,9):
                if (self.levelFinish[i+1]!=True):
                    self.screen.blit(self.lampred[i-6], lamp_pos[i] )
                    
        if self.difsel==3:
            if (self.levelFinish[1]!=True):
                self.screen.blit(self.fish1, (380,495)) 
            if (self.levelFinish[7]!=True):
                self.screen.blit(self.fish2, (340,520))
        
        
        if (self.bridge!=0) and (self.difsel==0):    
            self.screen.blit(self.image_bridgeEasy[self.bridge-1], (50,290))
        if (self.bridge!=0) and (self.difsel==1):    
            self.screen.blit(self.image_bridgeHard[self.bridge-1], (50,290))
        
        if self.difsel!=3:    
            self.screen.blit(self.image_wood1, (-30,553-75))
                
        self.screen.blit(self.image_statusbar, (0,877))
        
        font = pygame.font.Font(None, 24)#desenha os pontos na statusbar
        self.scoreMsg = font.render("Score : %d"%(self.score), True, [0,0,0])
        #self.scoreMsg = font.render("Pontos : %d"%(self.score), True, [0,0,0])
        self.screen.blit(self.scoreMsg, (1080,805))
        
        self.panel.statusMsg()
        
        if self.level!=0 :
            self.panel.draw( self.screen, self.difsel, self.level )

    def loop(self):
        """
        Keep the game in loop while self.run is True
        
        Here we have the end routine running too, when the all levels aew completed the game will show an end game screen
        
        @param self   QCMusical object
        
        """
        self.panel = Panel(self.level)

        clock = pygame.time.Clock()
        
        while self.run:
        
            clock.tick(20)

            self.actors_draw()

            self.handle_events()
            
            #print "FPS: %0.2f" % clock.get_fps() #to see game performace 
            
            #End game routine
            if (self.levelFinish==[True,True,True,True,True,True,False,True,True,True,False]):
                self.panel.msg="Press ESC to CLOSE the game."
                #self.panel.msg="Pressione ESC para fechar o jogo."
                self.difsel=5
                
                screenbox = pygame.Surface((1200,825)).convert_alpha()
                screenbox.fill((0,0,0,127))
                screenfont = pygame.font.Font(None, 96)
                smallfont = pygame.font.Font(None, 48)
                screentext = screenfont.render('You WIN!!!!', True, (255,255,255))
                screentext2 = smallfont.render('Congratulations you finish the Game!', True, (255,255,255))
                #screentext = screenfont.render('Voce Venceu!!!', True, (255,255,255))
                #screentext2 = smallfont.render('Parabens voce terminou o Jogo!', True, (255,255,255))


                self.screen.blit(screenbox, (0,0))
                self.screen.blit(screentext, self.screen.get_rect().center)
                self.screen.blit(screentext2, (400,475))
              
                #TODO: Restart func when space is pressed
           
            #update the entire screen (can be change if use dirty rectangles)
            pygame.display.update()
'''            
class StopGame(Exception):
    pass
    
class ExitGame(Exception):
    pass
   ''' 
                
def main():
    qcmusical = QCMusical()
    qcmusical.loop()


if __name__== '__main__':
    main()

